package com.demo.controller;

import com.demo.controller.base.BaseCtrl;
import com.demo.controller.model.RSResult;
import com.demo.core.ActionContext;
import com.demo.po.ApplicationPo;
import com.demo.service.IApplicationService;
import com.demo.service.IServerService;
import com.demo.service.common.BizException;
import com.demo.utils.ShellUtils;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/application")
public class ApplicationController extends BaseCtrl {

    private final IApplicationService applicationService;

    private final IServerService serverService;

    @Autowired
    public ApplicationController(IApplicationService applicationService, IServerService serverService) {
        this.applicationService = applicationService;
        this.serverService = serverService;
    }

    @PostMapping(value = "/list")
    @ResponseBody
    public RSResult list(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            int count = applicationService.countApplications(application);
            List<ApplicationPo> list = new ArrayList<>();
            if (count > 0) {
                application.setPagestart((application.getCurpage() - 1) * application.getPagesize());
                list = applicationService.findApplicationsByPage(application);
            }
            result.setResult(0);
            result.setTotal(count);
            result.setData(list);
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        }
        return result;
    }

    @PostMapping(value = "/detail")
    @ResponseBody
    public RSResult info(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            ApplicationPo obj = applicationService.getApplication(application.getApplicationid());
            result.setResult(0);
            result.setData(obj);
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        }
        return result;
    }

    @PostMapping(value = "/new")
    @ResponseBody
    public RSResult add(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            String remark = ActionContext.testApp(application);
            Integer id = applicationService.addApplication(application);
            result.setResult(0, remark);
            result.setData(id);
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        } catch (Exception ex) {
            ex.printStackTrace();
            result.setResult(-2, "执行脚本失败！");
        }
        return result;
    }

    @PostMapping(value = "/update")
    @ResponseBody
    public RSResult update(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            String remark = ActionContext.testApp(application);
            applicationService.updateApplication(application);
            result.setResult(0);
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        }
        return result;
    }

    @PostMapping("/test")
    public @ResponseBody
    RSResult testApplication(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            String remark = ActionContext.testApp(application);
            if (application.getApplicationid() != null && application.getApplicationid() > 0)
                applicationService.updateApplication(application);
            if (application.getAppstatus() == 0) {
                result.setResult(0, remark);
                result.setData(0);
            } else {
                result.setResult(-1, remark);
                result.setData(1);
            }
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        }
        return result;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public RSResult delete(@RequestBody ApplicationPo application) {
        RSResult result = new RSResult();
        try {
            applicationService.deleteApplication(application.getApplicationid());
            result.setResult(0);
        } catch (BizException ex) {
            log.error("{} : {}", ex.getErrorcode(), ex.getRemark());
            result.setResult(ex.getErrorcode(), ex.getRemark());
        }
        return result;
    }

    @PostMapping("/start")
    public @ResponseBody
    RSResult startApplication(@RequestBody ApplicationPo cond) {
        RSResult result = new RSResult(-1);
        ApplicationPo application = applicationService.getApplication(cond.getApplicationid());
        String remark = ActionContext.testApp(application);
        if (application.getAppstatus() == 1) {
            Session session = ActionContext.getSession(application.getServerid());
            List<String> list = ShellUtils.execCmd(session,
                    "cd " + cond.getDeveloppath() + " && sh a.sh start");
            if (list == null) {
                result.setResult(-1, remark);
            } else {
                result.setResult(0);
            }
        } else {
            result.setResult(-1, remark);
        }
        applicationService.updateApplication(application);
        return result;
    }

    @PostMapping("/stop")
    public @ResponseBody
    RSResult stopApplication(@RequestBody ApplicationPo cond) {
        RSResult result = new RSResult(-1);
        ApplicationPo application = applicationService.getApplication(cond.getApplicationid());
        String remark = ActionContext.testApp(application);
        if (application.getAppstatus() == 0) {
            Session session = ActionContext.getSession(application.getServerid());
            List<String> list = ShellUtils.execCmd(session,
                    "cd " + cond.getDeveloppath() + " && sh a.sh stop");
            if (list == null) {
                result.setResult(-1, remark);
            } else {
                result.setResult(0);
            }
        } else {
            result.setResult(-1, remark);
        }
        applicationService.updateApplication(application);
        return result;
    }

//    @PostMapping("/release")
//    public @ResponseBody
//    RSResult releaseApplication(@RequestBody ApplicationPo cond) {
//        log.debug("Start release application, param is {}", cond);
//        RSResult result = new RSResult(-1);
//        Integer applicationid = cond.getApplicationid();
//        if (applicationid == null) {
//            result.setResult(-1, "请求参数有误！");
//        }
//        ApplicationPo application = applicationService.getApplication(applicationid);
//        if (application == null || StringUtils.isEmpty(application.getDeveloppath())) {
//            result.setResult(-1, "应用部署路径有误！");
//            return result;
//        }
//        String name = cond.getName();
//        String uid = cond.getUid();
//        String fileName = uid + "-" + name;
//        String developpath = ParseUtils.formatFilePath(application.getDeveloppath() + Constants.FILE_SEPARATOR + name);
//        String savePath = getUploadPath() + Constants.FILE_SEPARATOR + fileName;
//        try {
//            // TODO备份
//            ShellUtils.uploadFile(ActionContext.getSession(application.getHost()), savePath, developpath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        result.setResult(0);
//        return result;
//    }
}
